package com.ronsai.umtrack.base;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ronsai.umtrack.MyApp;
import com.ronsai.umtrack.api.converter.GsonConverterFactory;
import com.ronsai.umtrack.api.interceptor.HttpCacheInterceptor;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class BaseApi {

    private static final int CONNECT_TIME_OUT = 5;
    private static final int READ_TIME_OUT = 10;

    public Retrofit getRetrofit(String baseUrl) {
        // OkHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS); //链接超时
        builder.writeTimeout(READ_TIME_OUT, TimeUnit.SECONDS);      //写操作超时
        builder.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);       //读操作超时
        //builder.proxy(Proxy.NO_PROXY);  //不代理
        //builder.retryOnConnectionFailure(true); //错误重连

        // https认证 如果要使用https且为自定义证书 可以去掉这两行注释，并自行配制证书。
        //builder.sslSocketFactory(SslContextFactory.getSSLSocketFactoryForOneWay());
        //builder.hostnameVerifier(new SafeHostnameVerifier());

        // 配置缓存
        File cacheFile = new File(MyApp.getContext().getCacheDir(), "cache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); // 100Mb
        builder.addNetworkInterceptor(new HttpCacheInterceptor());
        builder.cache(cache);

        // 请求日志拦截器
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(logInterceptor);

        // 创建Retrofit
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build();

        return retrofit;
    }
}
